#include "servertcp.h"
#include <QDataStream>
#include <QSettings>

ServerTCP::ServerTCP()
{

}

void ServerTCP::startServer() {
    if(this->listen(QHostAddress::Any, 2323)) {
        sql = new SqlRequest();
        qWarning()<<"startServer Start!";
    }
    else
    {
        qWarning()<<"startServer Error!!!";
    }
}

void ServerTCP::incomingConnection(qintptr socketDescriptor) {
    socket = new QTcpSocket;
    socket->setSocketDescriptor(socketDescriptor);
    connect(socket, &QTcpSocket::readyRead, this, &ServerTCP::slotReadyRead);
    connect(socket, &QTcpSocket::disconnected, this, &ServerTCP::slotClientDisconnected);
    SClient[socket->socketDescriptor()] = socket;
}

void ServerTCP::slotClientDisconnected()
{
    foreach (int i, SClient.keys()) {
       if(SClient[i]->state() == SClient[i]->UnconnectedState) {
           emit sig_dickconnect(sql->selNumSud(i));
           SClient[i]->close();
           SClient.remove(i);
       }
    }
}

void ServerTCP::slotReadyRead() {
    QJsonObject jsonObject;
    socket = (QTcpSocket*)sender();
    QDataStream entrance(socket);
    entrance.setVersion(QDataStream::Qt_5_12);
    if(entrance.status() == QDataStream::Ok) {
        while(socket->bytesAvailable()>0)
        {
            Data.clear();
            Data = socket->readAll();
            QJsonDocument jsonDocument(QJsonDocument::fromJson(Data));
            // Из которого выделяем объект в текущий рабочий QJsonObject
            jsonObject = jsonDocument.object();
            switch (jsonObject["command"].toInt()) {
            case 0:
                devices["device_name"] = jsonObject["deviceName"].toString();
                devices["device_socketConn"] = QString::number(socket->socketDescriptor());
                emit connect_judges(sql->addDevice(devices));
                break;
            case 1:
                emit perfomance_judges(sql->connectJudges(jsonObject));
                break;
            case 2:
                if (jsonObject["nomersud"].toInt() == 0) {
                    QJsonObject obj;
                    obj["comand"] = 6;
                    obj["numSud"] = sql->selNumSud(socket->socketDescriptor());
                    SendToCLient(obj);
                } else {
                    sql->ocenkiAdd(jsonObject);
                    emit read_ocenki();
                }
                break;
            case 20:
                devicesTimekeeper["device_name"] = jsonObject["deviceName"].toString();
                devicesTimekeeper["device_socketConn"] = QString::number(socket->socketDescriptor());
                deviceSocketTimekeeper = socket->socketDescriptor();
                connect_timekeeper(sql->addDevice(devicesTimekeeper));
                break;
            case 21:
                emit start_stop_timer();
                break;
//            case 30:
//                devicesParticipants["device_name"] = jsonObject["deviceName"].toString();
//                devicesParticipants["device_socketConn"] = QString::number(socket->socketDescriptor());
//                deviceSocketParticipants = socket->socketDescriptor();
//                connect_participants(sql->addDevice(devicesParticipants));
//                break;
//            case 31:
//                emit start_stop_timer();
//                break;
//            case 40:
//                qWarning()<<"40";
//                break;
            default:
                break;
            }
        }
    }
    else
    {
        qDebug()<<"DataStream error!!!";
    }
}

void ServerTCP::SendToCLient(QJsonObject obj) {
    QJsonDocument Doc(obj);
    QByteArray ba = Doc.toJson();
    QString msg = ba;
    Data.clear();
    QDataStream send(&Data, QIODevice::WriteOnly);
    send.setVersion(QDataStream::Qt_5_12);
    send << msg;
    foreach (int i, SClient.keys()) {
        if(deviceSocketTimekeeper != i)SClient[i]->write(msg.toUtf8());
    }
}

void ServerTCP::SendToDevice(QJsonObject obj) {
    QJsonDocument Doc(obj);
    QByteArray ba = Doc.toJson();
    QString msg = ba;
    Data.clear();
    QDataStream send(&Data, QIODevice::WriteOnly);
    send.setVersion(QDataStream::Qt_5_12);
    send << msg;
    SClient[obj["socket"].toInt()]->write(msg.toUtf8());
}



